#include "AddDirDialog.hpp"
#include "Logger.hpp"
#include <errno.h>

BEGIN_EVENT_TABLE(AddDirDialog, wxDialog)
EVT_BUTTON(ID_DialogOkButton, AddDirDialog::addDir)
EVT_BUTTON(ID_DialogCloseButton, AddDirDialog::close)
END_EVENT_TABLE()

AddDirDialog::AddDirDialog(const wxString &title, std::string ipath, ClientCommands icc, MainFrame *iparent)
: wxDialog(NULL, -1, title, wxDefaultPosition, wxSize(250, 100)) {
    parent = iparent;
    toServer = true;
    cc = icc;
    path = ipath;
    std::string strtemp = std::string(title.mbc_str()) + ": ";
    new wxStaticText(this, -1, wxString(strtemp.c_str(), wxConvUTF8),
            wxPoint(5, 5), wxDefaultSize);
    tc = new wxTextCtrl(this, ID_AddDirTextBox, wxT(""),
            wxPoint(5, 10 + DEFAULTTEXTBOXHEIGHT), wxSize(DEFAULTTEXTBOXWIDTH, DEFAULTTEXTBOXHEIGHT));

    okButton = new wxButton(this, ID_DialogOkButton, wxT("Ok"),
            wxPoint(5, 10 + DEFAULTTEXTBOXHEIGHT * 2), wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT));
    closeButton = new wxButton(this, ID_DialogCloseButton, wxT("Close"),
            wxPoint(5 + DEFAULTBUTTONWIDTH, 10 + DEFAULTTEXTBOXHEIGHT * 2), wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT));

    tc->SetFocus();
    Centre();
    ShowModal();
    Destroy();
}

AddDirDialog::AddDirDialog(const wxString &title, std::string ipath, MainFrame *iparent)
: wxDialog(NULL, -1, title, wxDefaultPosition, wxSize(250, 100)) {
    parent = iparent;
    toServer = false;
    path = ipath;
    std::string strtemp = std::string(title.mbc_str()) + ": ";
    new wxStaticText(this, -1, wxString(strtemp.c_str(), wxConvUTF8),
            wxPoint(5, 5), wxDefaultSize);
    tc = new wxTextCtrl(this, ID_AddDirTextBox, wxT(""),
            wxPoint(5, 10 + DEFAULTTEXTBOXHEIGHT), wxSize(DEFAULTTEXTBOXWIDTH, DEFAULTTEXTBOXHEIGHT));

    okButton = new wxButton(this, ID_DialogOkButton, wxT("Ok"),
            wxPoint(5, 10 + DEFAULTTEXTBOXHEIGHT * 2), wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT));
    closeButton = new wxButton(this, ID_DialogCloseButton, wxT("Close"),
            wxPoint(5 + DEFAULTBUTTONWIDTH, 10 + DEFAULTTEXTBOXHEIGHT * 2), wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT));

    tc->SetFocus();
    Centre();
    ShowModal();
    Destroy();
}

void AddDirDialog::addDir(wxCommandEvent& event) {
    path += tc->GetValue().mbc_str();
    if (toServer == true) {
        int rCode = 0;
        if ((rCode = cc.requestAddDir(path)) != 0) {
            parent->errorBox(rCode);
        }
    } else {
        if (mkdir(path.c_str(), 0700) != 0) {
            parent->errorBoxClient(errno);
        }
    }
    Destroy();
}

void AddDirDialog::close(wxCommandEvent& event) {
    Destroy();
}
